<?php
/**
 * @file $HeadURL: imagecollective.php $
 * @author $Author: DongJC (dongjianchang@haibao.com) $
 * @date $Date: 2015-3-30 9:02:55 $
 * @brief 
 */
namespace haibao\cms\data\imagecollective;

use \haibao\cms\model\data\imagecollective\ImageCollective as ImageCollectiveData;
use \haibao\cms\model\filter\imagecollective\ImageCollective as ImageCollectiveFilter;
use haibao\cms\web\view\app\article\Preview;

class ImageCollective extends \haibao\cms\data\BaseMysql{
	public function __construct(){
		parent::__construct('\haibao\cms\model\data\imagecollective\ImageCollective');
	}
	const PIC_CLICK = 7;
	public function searchIdsByKeywordFilter($filter){
		$ids = array();
		$sengine = new \haibao\cms\sengine\SphinxDb();
		$result = $sengine->search($filter);
		if (!empty($result['matches'])){
			$filter->getPager()->setResultCount($result['total']);
			foreach ($result['matches'] as $match){
				array_push($ids,$match['attrs']['recordid']);
			}
		}
		
		return $ids;
	}
	
	public function getBanners($parentTagId){
		$data = array();
		$parentTagId = $this->escape($parentTagId);
		$sql = 'SELECT distinct(t1.TagId) FROM ImageCollectiveTag t1 INNER JOIN ImageCollective t2 ON t1.ImageCollectiveId = t2.Id';
		$sql .= ' WHERE t1.ParentId='.$parentTagId;
		$sql .= ' and t1.IsPrimaiy = '.\haibao\cms\model\data\imagecollective\ImageCollectiveTag::IS_PRIMAIY;
		$sql .= ' and t1.TagId != '.$parentTagId;
		$sql .= ' and t2.PublishTime >= "'.date('Y-m-d',strtotime('-2 weeks',strtotime(date('Y-m-d')))).'"';
		$sql .= ' and t2.Published = '.ImageCollectiveData::PUBLISH_MOBILE_YES.' and t2.Status = '.ImageCollectiveData::STATUS_ENABLE;
		$sql .= ' ORDER BY t2.PublishTime desc LIMIT 0,10';
		$result = $this->query($sql);
		if ($result){
			$tagIds = array();
			while ($result->fetch_assoc()){
				array_push($tagIds,$result->getData('TagId'));
			}
			
			if ($tagIds){
				$tagData = new \haibao\cms\data\Tag();
				$tags = $tagData->getTagsById($tagIds);
				$data = array_values($tags);
			}
		}
		
		return $data;
	}
	
	public function getRecommendEightImageCollective($imageSetId){
		$data = array();
		$imageSetId = $this->escape($imageSetId);
		$sql = 'select t1.ParentId from ImageCollectiveTag t1 where t1.ImageCollectiveId = '.$imageSetId.' and t1.IsPrimaiy = 1';
		$result = $this->query($sql);
		$parentId = null;
		while ($result->fetch_assoc()){
			$parentId = $result->getData('ParentId');
		}
		
		//一个月，dev测试暂时不限制
		if ($parentId){
			$timeStart = date('Y-m-d',strtotime('-1 months'));
			$timeEnd = date('Y-m-d');
			//AND t5.PublishTime between '{$timeStart}' and '{$timeEnd}'
			$sql = <<<EOT
SELECT
	t1.Id,
	t1.Title,
	t2.ImageType,
	t3.Filename,
	t4.ClickNum,
	t8.ParentId
FROM
	ImageCollective t1
INNER JOIN ImageCollectivePro t2 ON t1.Id = t2.ImageCollectiveId
LEFT JOIN ImageLibrary t3 ON t2.ImageId = t3.Id
LEFT JOIN ImageCollectiveProperty t4 ON t1.Id = t4.ImageCollectiveId
left join ImageCollectiveTag t8 on t1.Id = t8.ImageCollectiveId
INNER JOIN (
	SELECT
		t5.Id
	FROM
		ImageCollective t5
	LEFT JOIN ImageCollectiveTag t6 ON t5.Id = t6.ImageCollectiveId
	LEFT JOIN ImageCollectiveProperty t7 ON t7.ImageCollectiveId = t5.Id
	WHERE
		t5.Published = 1
	AND t5. STATUS = 1
	AND t5.Id != {$imageSetId}
	AND t6.IsPrimaiy = 1
	AND t6.ParentId = {$parentId}
	AND t5.Level != 0
	AND t5.PublishTime between '{$timeStart}' and '{$timeEnd}'		
	ORDER BY
		t7.ClickNum DESC,
		t5.PublishTime DESC
	LIMIT 0,
	12
) a ON t1.Id = a.Id
EOT;
			$result = $this->query($sql);
			while ($result->fetch_assoc()){
				$id = $result->getData('Id');
			
				if (!isset($data[$id])){
					$model = new \haibao\cms\model\data\imagecollective\ImageCollective();
					$model->Id = $id;
					$model->Title = $result->getData('Title');
					$model->ImageCollectivePro = array();
					$model->TagId = $result->getData('ParentId');
					$data[$id] = $model;
				}
			
				$imageProModel = new \haibao\cms\model\data\imagecollective\ImageCollectivePro();
				$imageProModel->ImageType = $result->getData('ImageType');
				$imageProModel->FileName = $result->getData('Filename');
				array_push($data[$id]->ImageCollectivePro,$imageProModel);
			}
		}
		
		return $data;
	}
	
	public function getRecommendCollectives($imageCollectiveId,$tagId){
		$data = array();
		$imageCollectiveId = $this->escape($imageCollectiveId);
		$tagId = $this->escape($tagId);
		$sql = <<<EOT
select
	t1.Id,
	t1.Title,
	t2.ImageType,
	t3.Filename
from 
	ImageCollective t1
inner join ImageCollectivePro t2 on t1.Id = t2.ImageCollectiveId
left join ImageLibrary t3 on t2.ImageId = t3.Id
inner join (
	SELECT
		t1.Id,t3.ClickNum,t1.CreateTime
	FROM
		ImageCollective t1
	INNER JOIN ImageCollectiveTag t2 ON t1.Id = t2.ImageCollectiveId
	INNER JOIN ImageCollectiveProperty t3 ON t1.Id = t3.ImageCollectiveId
	WHERE
		t1.STATUS = 1
	AND t1.Published in (1,4)
	AND t2.IsPrimaiy = 1
	AND t2.TagId = {$tagId}
	AND t1.Id != {$imageCollectiveId}
	AND t1.Level != 0
	ORDER BY
		t3.ClickNum DESC,
		t1.PublishTime DESC
	limit 0,4
) a on a.Id = t1.Id
EOT;
		$result = $this->query($sql);
		while ($result->fetch_assoc()){
			$id = $result->getData('Id');
			
			if (!isset($data[$id])){
				$model = new \haibao\cms\model\data\imagecollective\ImageCollective();
				$model->Id = $id;
				$model->Title = $result->getData('Title');
				$model->ImageCollectivePro = array();
				$data[$id] = $model;
			}
			
			$imageProModel = new \haibao\cms\model\data\imagecollective\ImageCollectivePro();
			$imageProModel->ImageType = $result->getData('ImageType');
			$imageProModel->FileName = $result->getData('Filename');
			array_push($data[$id]->ImageCollectivePro,$imageProModel);
		}
		
		return $data;
	}
	
	public function getSiblingImageCollectives($imageCollectiveId,$parentId){
		$data = array();
		$imageCollectiveId = $this->escape($imageCollectiveId);
		$parentId = $this->escape($parentId);
		$sql = 'select PublishTime from ImageCollective where Id = '.$imageCollectiveId;
		$result = $this->query($sql);
		$publishTime = null;
		while ($row = $result->fetch_assoc()){
			$publishTime = $row['PublishTime'];
		}
		
		$sql = <<<EOT
SELECT
	t1.Id,
	t1.Title,
	t1.ShortTitle,
	t1.Description,
	t2.ImageType,
	t3.Filename as FileName,
	b.Type
FROM
	ImageCollective t1
INNER JOIN ImageCollectivePro t2 on t1.Id = t2.ImageCollectiveId
INNER JOIN ImageLibrary t3 on t2.ImageId = t3.Id
inner join (
	select Type,Id from
	(
		(
			SELECT
				'prev' as Type,
				t4.Id
			FROM
				ImageCollective t4
			INNER JOIN ImageCollectiveTag t5 ON t4.Id = t5.ImageCollectiveId
			AND t5.IsPrimaiy = 1 AND t5.ParentId = {$parentId}
			where t4.Status = 1 and t4.Level != 0 and t4.Published = 1 and t4.PublishTime < '{$publishTime}' order by t4.PublishTime desc limit 0,1
		)
		union all 
		(
			SELECT
				'next' as Type,
				t6.Id
			FROM
				ImageCollective t6
			INNER JOIN ImageCollectiveTag t7 ON t6.Id = t7.ImageCollectiveId
			AND t7.IsPrimaiy = 1 AND t7.ParentId = {$parentId}
			where t6.Status = 1 and t6.Level != 0 and t6.Published = 1 and t6.PublishTime > '{$publishTime}' order by t6.PublishTime asc limit 0,1
		)
	) a
) b on b.Id = t1.Id
EOT;
		$result = $this->query($sql);
		
		while ($result->fetch_assoc()){
			$type = $result->getData('Type');
			if (!isset($data[$type])){
				$imageCollectiveModel = new \haibao\cms\model\data\imagecollective\ImageCollective();
				$imageCollectiveModel->Id = $result->getData('Id');
				$imageCollectiveModel->Title = $result->getData('Title');
				$imageCollectiveModel->ShortTitle = $result->getData('ShortTitle');
				$imageCollectiveModel->Description = $result->getData('Description');
				$imageCollectiveModel->ImageCollectivePro = array();
				$data[$type] = $imageCollectiveModel;
			}
			
			$imageCollectiveProModel = new \haibao\cms\model\data\imagecollective\ImageCollectivePro();
			$imageCollectiveProModel->ImageType = $result->getData('ImageType');
			$imageCollectiveProModel->FileName = $result->getData('FileName');
			array_push($data[$type]->ImageCollectivePro,$imageCollectiveProModel);
		}

		return $data;
	}
	
	public function getIndexImageCollectiveByBannerIds($bannerIds){
		$data = array();
		if ($bannerIds){
			$bannerIdStr = implode(',',$bannerIds);
			$sql = <<<EOT
SELECT
 t1.Id as t1Id,
 t1.Title AS t1Title,
 t1.ShortTitle AS t1ShortTitle,
 t1.Description AS t1Description,
 t1.CreateTime AS t1CreateTime,
 t2.ImageId AS t2ImageId,
 t2.Description AS t2Description,
 t2.ImageType AS t2ImageType,
 t3.ParentId AS t3ParentId,
 t6.Filename as t6Filename,
 t7.ClickNum as t7ClickNum,
 t7.PcClickNum as t7PcClickNum,
 t7.MobileClickNum as t7MobileClickNum,
 t7.CommentNum as t7CommentNum
FROM
 ImageCollective t1
INNER JOIN ImageCollectivePro t2 ON t1.Id = t2.ImageCollectiveId
INNER JOIN ImageCollectiveTag t3 ON t1.Id = t3.ImageCollectiveId
INNER JOIN ImageLibrary t6 on t2.ImageId = t6.Id	
LEFT JOIN ImageCollectiveProperty t7 on t7.ImageCollectiveId = t1.Id
WHERE
 t1.Status = 1
 AND t1.Level != 0
 AND t1.Published = 1
 AND t3.ParentId IN ({$bannerIdStr})
AND 6 > (
 SELECT
  count(*)
 FROM
  ImageCollective t4
 INNER JOIN ImageCollectiveTag t5 ON t4.Id = t5.ImageCollectiveId
 WHERE
  t5.ParentId = t3.ParentId
 AND t4.Status = 1
 AND t4.Level != 0
 AND t4.Published = 1
 AND t4.PublishTime > t1.PublishTime
)
ORDER BY
 t3.ParentId,
 t1.PublishTime DESC		
EOT;
		$result = $this->query($sql);
		while ($row = $result->fetch_assoc()){
			$bannerId = $result->getData('t3ParentId');
			if (!isset($data[$bannerId])){
				$data[$bannerId] = array();
			}
			
			$imageCollectiveId = $result->getData('t1Id');
			if (!isset($data[$bannerId][$imageCollectiveId])){
				$data[$bannerId][$imageCollectiveId] = array();
				$imageCollectiveModel = new \haibao\cms\model\data\imagecollective\ImageCollective();
				$imageCollectiveModel->Id = $imageCollectiveId;
				$imageCollectiveModel->Title = $result->getData('t1Title');
				$imageCollectiveModel->ShortTitle = $result->getData('t1ShortTitle');
				$imageCollectiveModel->Description = $result->getData('t1Description');
				$imageCollectiveModel->CreateTime = $result->getData('t1CreateTime');
				$imageCollectiveModel->ImageCollectivePro = array();
				
				$imageCollectiveProperty = new \haibao\cms\model\data\imagecollective\ImageCollectiveProperty();
				$imageCollectiveProperty->ClickNum = intval($result->getData('t7ClickNum'));
				$imageCollectiveProperty->PcClickNum = intval($result->getData('t7PcClickNum'));
				$imageCollectiveProperty->MobileClickNum = intval($result->getData('t7MobileClickNum'));
				$imageCollectiveProperty->CommentNum = intval($result->getData('t7CommentNum'));
				
				$imageCollectiveModel->Property = $imageCollectiveProperty;
				$data[$bannerId][$imageCollectiveId] = $imageCollectiveModel;
			}

			$imageCollectivePro = new \haibao\cms\model\data\imageCollective\ImageCollectivePic();
			$imageCollectivePro->ImageId = $result->getData('t2ImageId');
			$imageCollectivePro->Description = $result->getData('t2Description');
			$imageCollectivePro->ImageType = $result->getData('t2ImageType');
			$imageCollectivePro->FileName = $result->getData('t6Filename');
			
			array_push($imageCollectiveModel->ImageCollectivePro,$imageCollectivePro);}
		}
		
		return $data;
	}
	
	public function imageCollectiveDate($model){
		self::beginTranscation ();
		try{
			$this->add($model);			
			
			
			
			
			$channelTagId = $this->saveRelationTable($model);
			$this->savePropertyTable($model->Id);
			$this->addWapImageColl($model, $channelTagId);
		}catch (\Exception $e){
			$this->rollback ();
			throw $e;
		}	
		$this->endTranscation ();
		
	}
	
	public function updateCollectiveDate($model,$oldPublished){	
		try{
			$this->updateById($model->Id, array(
					ImageCollectiveFilter::CONDITION_FIELD_NAME_CATEGORY_ID=>$model->CategoryId,
					ImageCollectiveFilter::CONDITION_FIELD_NAME_DESCRIPTION=>$model->Description,
					ImageCollectiveFilter::CONDITION_FIELD_NAME_TITLE=>$model->Title,
					ImageCollectiveFilter::CONDITION_FIELD_NAME_LEVEL=>$model->Level,
					ImageCollectiveFilter::CONDITION_FIELD_NAME_SHORT_TITLE=>$model->ShortTitle,
					ImageCollectiveFilter::CONDITION_FIELD_NAME_STATUS=>$model->Status,
					ImageCollectiveFilter::CONDITION_FIELD_NAME_IMAGE_COLLECTIVE_PUBLISHED=>$model->Published,
					ImageCollectiveFilter::CONDITION_FIELD_NAME_IMAGE_COLLECTIVE_PUBLISHTIME=>$model->PublishTime,
					ImageCollectiveFilter::CONDITION_FIELD_NAME_INDEX_TIME=>$model->IndexTime
					));

			
			$channelTagId = $this->saveRelationTable($model);
			$this->addWapImageColl($model, $channelTagId);

			if($oldPublished != $model->Published && $model->Published == \haibao\cms\model\data\imagecollective\ImageCollective::STATUS_NO_PUBLISH){
				$data = new \haibao\cms\data\Article();
				$data->deleteInfomation($model->Id,\haibao\cms\model\data\InformationBrand::INFO_TYPE_PIC);
				//操作聚合记录
				$polymerInfoData = new \haibao\cms\data\PolymerInfo();
				$polymerInfoData->updatePolymarInfo($model->Id,\haibao\cms\model\data\PolymerInfo::OBJECT_TYPE_IMAGE,array('Status'=>\haibao\cms\model\data\PolymerInfo::STATUS_DEL));
			}
		}catch (\Exception $e){
			$this->rollback ();
			throw $e;
		}		
	}
	
	public function getImageCollectiveIsPublish($imageCollectiveId){
		$sql = "select Id from ImageCollective where Id=%s and Published=%s";
		$data  = $this->query($sql,array($imageCollectiveId,\haibao\cms\model\data\imagecollective\ImageCollective::STATUS_YES_PUBLISH));
		$result = false;
		while ($data->fetch_assoc()){
			$result = true;
		}
		return $result;
	}
	
	/**
	 * 同步添加手机端图集数据
	 * @param unknown $imageCollectiveId
	 * @param unknown $status
	 */
	private function addWapImageColl($imageCollectiveModel,$channelTagId){
		//$imageCollectiveData = $this->getOneById($imageCollectiveModel->Id);
		if(!$imageCollectiveModel->IsPostMobile && $imageCollectiveModel->Level > 0 && $imageCollectiveModel->Published && $imageCollectiveModel->Status == \haibao\cms\model\data\imagecollective\ImageCollective::STATUS_ENABLE){
			$wapInfoModel = new \haibao\cms\model\data\WapInfo();
			$wapInfoModel->InfoId = $imageCollectiveModel->Id;
			$wapInfoModel->Title = $imageCollectiveModel->Title;
			if(empty($imageCollectiveModel->CreateBy) || empty($imageCollectiveModel->CreateTime)){
				$imageCollectiveInfo = $this->getOneById($imageCollectiveModel->Id);
				$wapInfoModel->CreateBy = $imageCollectiveInfo->CreateBy;
				$wapInfoModel->CreateTime = $imageCollectiveInfo->CreateTime;
			} else {
				$wapInfoModel->CreateBy = $imageCollectiveModel->CreateBy;
				$wapInfoModel->CreateTime = $imageCollectiveModel->CreateTime;
			}
			
			$wapInfoModel->Author = $imageCollectiveModel->Author;
			
			$wapInfoModel->Published = $wapInfoModel::PUBLISHED_YES;
			$wapInfoModel->PublishTime = $imageCollectiveModel->PublishTime;
			$wapInfoModel->PublishId = $imageCollectiveModel->Id;
			$wapInfoModel->Level = $imageCollectiveModel->Level;
			$wapInfoModel->InfoType = $wapInfoModel::INFO_TYPE_IMAGE_COLLECTIVE;
			$wapInfoModel->TagId = $channelTagId;
			$wapInfoModel->IndexTop = $wapInfoModel::INDEX_TOP_NO;
			$wapInfoModel->ChannelTop = $wapInfoModel::CHANNEL_TOP_NO;
			
			$this->add($wapInfoModel);
			$sql = "update ImageCollective set IsPostMobile=%s where Id=%s";
			$this->query($sql,array(\haibao\cms\model\data\Article::PUBLISH_MOBILE_YES,$imageCollectiveModel->Id));
		}
		if($imageCollectiveModel->IsPostMobile){
			if($imageCollectiveModel->Published){
				$sql = 'update WapInfo set Title=%s,Level=%s,TagId=%s,PublishTime=%s where InfoId=%s and InfoType=%s';
				$this->query($sql,array($imageCollectiveModel->Title,$imageCollectiveModel->Level,$channelTagId,$imageCollectiveModel->PublishTime,$imageCollectiveModel->Id,\haibao\cms\model\data\WapInfo::INFO_TYPE_IMAGE_COLLECTIVE));
			} else {
				$sql = 'delete from WapInfo where InfoId=%s and InfoType=%s';
				$this->query($sql,array($imageCollectiveModel->Id,\haibao\cms\model\data\WapInfo::INFO_TYPE_IMAGE_COLLECTIVE));
			
				$sql = "update ImageCollective set IsPostMobile=%s where Id=%s";
				$this->query($sql,array(\haibao\cms\model\data\Article::PUBLISH_MOBILE_NO,$imageCollectiveModel->Id));
			}
		}
	}
	
	public function updateImageCollectiveStatus($imageCollectiveId,$status){
		$sql="update ImageCollective set Status = %s where Id = %s";		
		$this->query($sql,array($status,$imageCollectiveId));
	}
	
	/**
	 * 根据图集ID得主标签对应的父级标签ID
	 * @param unknown_type $imageCollectiveId
	 */
	public function getParentTagIdByImageCollectiveId($imageCollectiveId){
		$parentTagId = 0;
		$sql = "select ParentId from ImageCollectiveTag where ImageCollectiveId = %s and IsPrimaiy=1";
		$result = $this->query($sql,array($imageCollectiveId));
		while($result->fetch_assoc()){
			$parentTagId = $result->getData('ParentId');
		}
		
		return $parentTagId;
	}
	
	public function delImageCollectiveById($id,$published){
		$this->beginTranscation();
		try{
			if($published != \haibao\cms\model\data\imagecollective\ImageCollective::STATUS_NO_PUBLISH){
				$data = new \haibao\cms\data\Article();
				$data->deleteInfomation($id,\haibao\cms\model\data\InformationStar::INFO_TYPE_PIC);
				
				//操作聚合记录
				$polymerInfoData = new \haibao\cms\data\PolymerInfo();
				$polymerInfoData->updatePolymarInfo($id,\haibao\cms\model\data\PolymerInfo::OBJECT_TYPE_IMAGE,array('Status'=>\haibao\cms\model\data\PolymerInfo::STATUS_DEL));
			}
			
			$ids = "";
			if(is_array($id)){
				$ids = join(',', $id);
			}else{
				$ids = intval($id);
			}
			$status = ImageCollectiveData::STATUS_DEL_ENABLE;
			$publised = ImageCollectiveData::STATUS_NO_PUBLISH;
			$sql="update ImageCollective set Status = $status , Published = $publised where Id in ($ids) ";
			$this->query($sql);
			
		}catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	
	public function haveImageCollectivePro($id){
		$sql="select count(Id) as count from ImageCollectivePro where ImageCollectiveId = %s";
		$result = $this->query($sql,array($id));
		while($result->fetch_assoc()){
			if($result->getData('count')){
				return false;
			}else{
				return true;
			}
		}
		return false;
	}
	
	private function savePropertyTable($collectiveId){
		$sql="insert into ImageCollectiveProperty (ImageCollectiveId,ClickNum,PcClickNum,MobileClickNum,CommentNum,EditClickNum,ShareNum) values (".$collectiveId.",0,0,0,0,0,0)";
		$this->query($sql);
	}
	
	public function saveImageCollectivePic($model){
		$insertArray = array();
		$itemArray = array();
		if($model->ImageCollectivePic){
			$sql="insert into ImageCollectivePic (ImageCollectiveId,ImageId,Description,PicOrder) values ";
			$order = 1;
			foreach($model->ImageCollectivePic as $key =>$picModel){
				if(empty($picModel->ImageCollectiveId)){
					$picModel->ImageCollectiveId = $model->Id;
				}
				array_push($itemArray,'(%s,%s,%s,%s)');
				array_push($insertArray,$picModel->ImageCollectiveId);
				array_push($insertArray,$picModel->ImageId);
				array_push($insertArray,$picModel->Description);
				array_push($insertArray,$order);
				$order++;
			}
			$sql.=join(',',$itemArray);
			$this->query($sql,$insertArray);
		}	
	}
	
	public function saveAllImageCollectivePic($model){
	    $insertArray = array();
	    $itemArray = array();
	    if($model[0]['ImageCollectiveId']){
	        $sql="insert into ImageCollectivePic (ImageCollectiveId,ImageId,Description,PicOrder) values ";
	        $order = 1;
	        foreach($model as $key =>$picModel){
	            array_push($itemArray,'(%s,%s,%s,%s)');
	            array_push($insertArray,$picModel['ImageCollectiveId']);
	            array_push($insertArray,$picModel['ImageId']);
	            array_push($insertArray,$picModel['Description']);
	            array_push($insertArray,$order);
	            $order++;
	        }
	        $sql.=join(',',$itemArray);
	        $this->query($sql,$insertArray);
	    }
	}
	
	public function saveImageCollectivePro($model){
		$insertArray = array();
		$itemArray = array();
		if($model->ImageCollectivePro){		
			$sql="delete from ImageCollectivePro where ImageCollectiveId  = %s and ImageType=".$model->ImageCollectivePro->ImageType." ";
			$this->query($sql,array($model->Id));
			$sql="insert into ImageCollectivePro (ImageCollectiveId,ImageId,ImageType,CreateBy,CreateTime) values ";
		
			array_push($itemArray,'(%s,%s,%s,%s,%s)');
			array_push($insertArray,$model->Id);
			array_push($insertArray,$model->ImageCollectivePro->ImageId);
			array_push($insertArray,$model->ImageCollectivePro->ImageType);
			array_push($insertArray,$model->ImageCollectivePro->CreateBy);
			array_push($insertArray,$model->ImageCollectivePro->CreateTime);
		
			$sql.=join(',',$itemArray);
			$this->query($sql,$insertArray);
			
			//操作聚合页面
			$polymerInfoData = new \haibao\cms\data\PolymerInfo();
			$polymerInfoModel = $polymerInfoData->getPolymerInfo($model->Id,\haibao\cms\model\data\PolymerInfo::OBJECT_TYPE_IMAGE);
			if(!empty($polymerInfoModel) && $polymerInfoModel->Status == \haibao\cms\model\data\PolymerInfo::STATUS_OK){
				$arrSet = array();
				$arrSet['UpdateType'] = \haibao\cms\model\data\PolymerInfo::UPDATE_TYPE_TITLE;
				$arrSet['Status'] = \haibao\cms\model\data\PolymerInfo::STATUS_EDIT;
				$polymerInfoData->updatePolymarInfo($model->Id,\haibao\cms\model\data\PolymerInfo::OBJECT_TYPE_IMAGE,$arrSet);
			}
		}
	}
	
	public function delImageCollectivePic($id,$imageIds=null){
		try{
			if($imageIds){
				if(is_array($imageIds)){
					$imageString = explode(',', $imageIds);
					$sql="delete from ImageCollectivePic where ImageId in ($imageString)  and ImageCollectiveId = %s ";
				}else{
					$sql="delete from ImageCollectivePic where ImageId = $imageIds  and ImageCollectiveId = %s ";
				}
			}else{
				$sql="delete from ImageCollectivePic where ImageCollectiveId = %s ";
			}
			$this->query($sql,array($id));
		}catch (\Exception $e){
			$this->rollback ();
			throw $e;
		}
	}
	
	public function delAllImageCollectivePic($id){
	    if($id){
	        $sql="delete from ImageCollectivePic where ImageCollectiveId = %s ";
	        $this->query($sql,array($id));
	    }
	    
	}
	
	/**
	 * 批量修改状态
	 * @param unknown $imageIdStr
	 * @param unknown $desc
	 * @param unknown $imageCollectiveId
	 */
	public function updateBatch($imageIdStr,$desc,$imageCollectiveId){
		$sql="update ImageCollectivePic set Description = %s where ImageCollectiveId = %s and ImageId in (".$imageIdStr.") ";
		$this->query($sql,array($desc,$imageCollectiveId));
	}
	
	public function batchUpdateTag($model){
		$itemArray = array();
		$insertArray = array();
		if($model && $model->ImageCollectiveTag){		
			$sql="insert into ImageCollectiveTag (ImageCollectiveId,TagId,IsPrimaiy,ParentId) values";
			foreach($model->ImageCollectiveTag as $key => $value){
				foreach($value as $k =>$val){
					array_push($itemArray,'(%s,%s,%s,%s)');
					array_push($insertArray,$val->ImageCollectiveId);
					array_push($insertArray,$val->TagId);
					array_push($insertArray,$val->IsPrimaiy);
					array_push($insertArray,$val->ParentId);
				}
			}
			$sql.=join(',',$itemArray);
			$this->query($sql,$insertArray);			
		}		
	}
	
	public function delImageCollectivePro($imageId,$type,$imageCollectiveId){
		$imageId = 0;
		$sql="select ImageId from ImageCollectivePic where ImageCollectiveId = %s order by Id asc limit 1";
		$result = $this->query($sql,array($imageCollectiveId));
		while($result->fetch_assoc()){
			$imageId = $result->getData('ImageId');
		}
		if($imageId){
			$sql="update ImageCollectivePro set ImageId = ".$imageId." where id ";
			$result = $this->query($sql);
		}
		
	}
	public function getImagesByIds($imageCollectiveIds){
		$str = preg_replace('/(\d+)/is', "%s", implode(',', $imageCollectiveIds));
		$sql = "select ImageId,ImageCollectiveId from ImageCollectivePic where ImageCollectiveId in(".$str.")";
		$result  = $this->query($sql,$imageCollectiveIds);
		$imageIds = array();
		while($result->fetch_assoc()){
			$imageIds[$result->getData('ImageCollectiveId')][] = $result->getData('ImageId');
		}
		return $imageIds;
	}
	
	/**
	 * 获取图集导读图
	 */
	public function getProImageFigure($imageCollectiveIds,$type){
		$str = preg_replace('/(\d+)/is', "%s", implode(',', $imageCollectiveIds));
		$sql = "select ImageId,ImageType,ImageCollectiveId from ImageCollectivePro where ImageCollectiveId in(".$str.")";
		$result  = $this->query($sql,$imageCollectiveIds);
		$imageProFigure = array();
		while($result->fetch_assoc()){
			$imageProFigure[$result->getData('ImageCollectiveId')][$result->getData('ImageType')] = $result->getData('ImageId');
		}
		$imageIds = array();
		if(!empty($imageProFigure)){
			foreach($imageProFigure as $key=>$proFigure){
				if(isset($proFigure[$type])){
					$imageIds[$key] = $proFigure[$type];
				}else{
					if(!empty($proFigure[\haibao\cms\model\data\imagecollective\ImageCollectivePro::IMAGE_TYPE_ZERO])){
						$imageIds[$key] = $proFigure[\haibao\cms\model\data\imagecollective\ImageCollectivePro::IMAGE_TYPE_ZERO];
					}
				}
			}
		}
		return $imageIds;
	}
	/**
	 * 获取为0的导读图
	 */
	public function getProImageLevelZero($collectiveId){
		$sql = "select ImageId from ImageCollectivePro where ImageType=0 and ImageCollectiveId = %s limit 1";
		$result = $this->query($sql,array($collectiveId));
		while ($result->fetch_assoc()){
			$imageId = $result->getData('ImageId');
		}
		return $imageId;
	}
	/**
	 * 通过图集ids 获得点击数评论数
	 */
	public function getClickCommentNumsByImgCollIds($imageCollectiveIds){
		if(!$imageCollectiveIds){
			return false;
		}

		$imageCollectiveList = array();
		$imageCollectiveIds = (array)$imageCollectiveIds;
		$imageCollectiveIds = array_chunk($imageCollectiveIds, 10);
		foreach($imageCollectiveIds as $imageCollectiveId){
			$data = $this->getImageCollClickByIds($imageCollectiveId);
			$imageCollectiveList +=$data;
		}
		return $imageCollectiveList;
		
		
	}
	
	public function getImageColletiveByIds($imageCollectiveIds){
	    $sql = 'select Id,PublishTime from ImageCollective where Id in ('.implode(',',$imageCollectiveIds).') and Status = 1 and Published = 1';
	    $result = $this->query($sql,$imageCollectiveIds);
	    $infoList = array();
	    while($row = $result->fetch_assoc()){
	        $infoList[$row['Id']] = $row['PublishTime'];
	    }
	    return $infoList;
	}
	
	
	public function getImageCollectivesByIds($imageCollectiveIds){
	    $sql = 'select a.Id,a.PublishTime,b.ParentId from ImageCollective as a left join ImageCollectiveTag as b on a.Id = b.ImageCollectiveId where a.Id in ('.implode(',',$imageCollectiveIds).') and a.Status = 1 and a.Published = 1';
	    $result = $this->query($sql,$imageCollectiveIds);
	    $infoList = array();
	    while($row = $result->fetch_assoc()){
	        $infoList[$row['Id']] = $row['ParentId'];
	    }
	    return $infoList;
	}
	
	private function getImageCollClickByIds($imageCollectiveIds){

		$imageCollectiveIdsStr = implode(',', $imageCollectiveIds);
		$str = preg_replace('/(\d+)/', '%s', $imageCollectiveIdsStr);
		$sql = "select ImageCollectiveId,ClickNum,EditClickNum,CommentNum,MobileClickNum,PcClickNum,CommentPariseNum,QuestionNum,QuestionPariseNum from ImageCollectiveProperty where ImageCollectiveId IN (".$str.")";
		$result = $this->query($sql, $imageCollectiveIds);
		$data = array();
		while ($result->fetch_assoc()){
			if(!isset($data[$result->getData('ImageCollectiveId')])){
				$nums = array(
						'clickNum'=>$result->getData('ClickNum'),
						'editClickNum'=>$result->getData('EditClickNum'),
						'commentNum'=>$result->getData('CommentNum')+$result->getData('CommentPariseNum')+$result->getData('QuestionNum')+$result->getData('QuestionPariseNum'),
						'pcClickNum'=>$result->getData('PcClickNum'),
						'mobileClickNum'=>$result->getData('MobileClickNum')
				);
				$data[$result->getData('ImageCollectiveId')] = $nums;
			}
		}
		return $data;
	}
	
	public function updateEditClickNumById($imageCollectiveId, $num) {
		$sql = 'update ImageCollectiveProperty set EditClickNum=%s where ImageCollectiveId=%s';
		$arrValues = array (
				$num,
				$imageCollectiveId
		);
		$this->query ( $sql, $arrValues );
	}
	
	public function getCronImageCollective(){
		$imageCollectiveId = array();
		$today = date('Y-m-d H:i:s',time());
		$sql="select Id from ImageCollective where Published=2 and PublishTime<='".$today."' ";
        $result = $this->query($sql,array());
		while($result->fetch_assoc()){
			$imageCollectiveId[] = $result->getData('Id');
		}		
		return $imageCollectiveId;
	}
    
    public function getCronImageCollectiveIng(){
        
        $imageCollectiveId = array();
		$sql="select Id from ImageCollective where Published=%s order by Id DESC";
		$result = $this->query($sql,array(\haibao\cms\model\data\imagecollective\ImageCollective::STATUS_PUBLISH_ING));
		while($result->fetch_assoc()){
			$imageCollectiveId[] = $result->getData('Id');
		}		
		return $imageCollectiveId;
	}
    
    
	/**
	 * 发布图集
	 * @param unknown $imageCollectiveId
	 * @param unknown $published
	 */
	public function updateArticlePublish($imageCollectiveId, $published = \haibao\cms\model\data\imagecollective\ImageCollective::STATUS_YES_PUBLISH){
		$sql = "";
		if (is_int ( $imageCollectiveId )) {
			$sql = "update ImageCollective set Published=%s where  Id=%s  ";
			$arrValues = array (
					$published,
					$imageCollectiveId
			);
			$this->query ( $sql, $arrValues );
		} elseif (is_array ( $imageCollectiveId )) {
			$Ids = join(',',$imageCollectiveId);
			$sql = "update ImageCollective set Published=".$published." where Id in (".$Ids.")  ";
			$this->query ( $sql );
		}
	}
	
	/**
	 * 设置图集点击数
	 */
	public function updateImageCollectiveClickNum($imageCollectiveId,$fromPc = true){
	    $this->dealPicClickNumData($imageCollectiveId,self::PIC_CLICK,$fromPc);
	    
	    $this->addInfoClickNumData($imageCollectiveId,2);
// 		$setStr = '';
// 		if($fromPc){
// 			$setStr = ',PcClickNum=PcClickNum+1';
// 		} else {
// 			$setStr = ',MobileClickNum=MobileClickNum+1';
// 		}
// 		$sql = "update ImageCollectiveProperty set ClickNum=ClickNum+1,EditClickNum=EditClickNum+1".$setStr." where ImageCollectiveId=%s";
// 		$result  = $this->query($sql,array($imageCollectiveId));
	}
	
	
	public function dealPicClickNumData($imageCollectiveId,$type,$fromPc = true){
	    $dataList = array();
	    $dataList['imageCollectiveId'] = $imageCollectiveId;
	    $dataList['time'] = time();
	    if(!$fromPc){
	        $dataList['wap'] = 1;
	    }
	    $cacheData = new \haibao\cms\cache\ImageLibrary();
	    $cacheData->setPicProperty($dataList);
	}
	
	public function addInfoClickNumData($infoId,$infoType){
	    $dataList = array();
	    $dataList['infoId'] = $infoId;
	    $dataList['infoType'] = $infoType;
	    $dataList['time'] = time();
	    $cacheData = new \haibao\cms\cache\Article();
	    $cacheData->setImageCollClickNum($dataList);
	}
	
	/**
	 * 设置图集分享数
	 * @param unknown_type $articleId
	 */
	public function updateImageCollectiveShareNum($imageCollectiveId){
		$sql = "update ImageCollectiveProperty set ShareNum=ShareNum+1 where ImageCollectiveId=%s";
		$result  = $this->query($sql,array($imageCollectiveId));
	}

	/**
	 * 根据id获取图集点击数
	 */
	public function getImageCollectiveClickNum($imageCollectiveId){
		$sql = 'select EditClickNum from ImageCollectiveProperty where ImageCollectiveId = %s';
		return $this->query($sql,array($imageCollectiveId))->fetch_assoc();
	}
	
	/**
	 * 根据图集id修改点击量
	 */
	public function editImageCollectiveClickNum($imageCollectiveId,$editClickNum){
		$sql = "update ImageCollectiveProperty set EditClickNum = %s where ImageCollectiveId=%s";
		$this->query($sql,array($editClickNum,$imageCollectiveId));
	}
	
	public function getLastIdByCate($categoryIds){
		$data = array();
		$i = 0;
		if($categoryIds){
			//$sql="select max(Id) as Id from ImageCollective where Published=1 and CategoryId in (".$categoryIds.") group by CategoryId limit 0,4";
			$sql="SELECT
						IC.Title,
						IC.ShortTitle,
						IC.Id,
						ICTag.TagId
					FROM
						ImageCollective AS IC
					INNER JOIN ImageCollectiveTag AS ICTag ON IC.Id = ICTag.ImageCollectiveId
					WHERE
						IC.Published = 1
					AND IC.`Status` = 1
					AND ICTag.TagId IN (".$categoryIds.")
					GROUP BY
						ICTag.TagId";
			$result  = $this->query($sql);
		}		
		while($result->fetch_assoc()){
			$data[$i]['Id'] = $result->getData('Id');
			$data[$i]['TagId'] = $result->getData('TagId');
			$data[$i]['Title'] = $result->getData('Title');
			$data[$i]['ShortTitle'] = $result->getData('ShortTitle');
			$i++;
		}
		return $data;
	}
	
	public function editImageOrder($model){
		try{
			$this->delImageCollectivePic($model->Id);
			$this->saveImageCollectivePic($model);
		}catch (\Exception $e){
			$this->rollback ();
			throw $e;
		}
	}
	
	public function addChoiceImage($model){
	    try{
	        if($model[0]['ImageCollectiveId']){
	            $this->delAllImageCollectivePic($model[0]['ImageCollectiveId']);
	            $this->saveAllImageCollectivePic($model);
	        }
	    }catch (\Exception $e){
	        $this->rollback ();
	        throw $e;
	    }
	}
	
	public function getStatisticList($queryArr,$isEditorSta = true){
	    $imageCollectiveList = array();
	    $imageCollectiveListCount = 0;
		$sql="select count(distinct Marst.Id) as ImageCollectiveNum,sum(Property.ClickNum) as ClickNum,sum(Property.PcClickNum) as PcClickNum,sum(Property.MobileClickNum) as MobileClickNum,sum(Property.CommentNum) as CommentNum,sum(Property.ShareNum) as ShareNum from ImageCollective as Marst ";
		$sql.=" left join ImageCollectiveProperty as Property on Marst.Id = Property.ImageCollectiveId";
		if(!empty($queryArr['tagIds'])){
			$sql.=" left join ImageCollectiveTag as Tag on Marst.Id = Tag.ImageCollectiveId";
		}
		$sql .= " where Marst.CreateBy<>477";
		if(!empty($queryArr['createBy'])){
			if(is_array($queryArr['createBy'])){
				$sql .= " And Marst.CreateBy in (".implode(',', $queryArr['createBy']).")";
			} else {
				$sql .= " And Marst.CreateBy = ".$queryArr['createBy'];
			}
		}
		if(!empty($queryArr['tagIds'])){
			$sql .= " And Tag.TagId in (".$queryArr['tagIds'].")";
		}
	
		if(isset($queryArr['Level'])){
			$level = (int)$queryArr['Level'];
			if($level <= 7){
				$sql .= " And Marst.Level = ".$level;
			} else {
				$level = $level - 7;
				$sql .= " And Marst.Level >= ".$level;
			}
		}
		if(!empty($queryArr['title'])){
			$sql .= " And Marst.Title like '%".$queryArr['title']."%'";
		}
		
		if(!empty($queryArr['publishTimeType'])){
			$publishTimeType = (int)$queryArr['publishTimeType'];
			switch ($publishTimeType){
				case 1:
					$sql .= " And Marst.PublishTime >= '".date('Y-m-d', strtotime('-1 day'))."' And Marst.PublishTime <= '".date('Y-m-d',time())."'";
					break;
				case 2:
					$sql .= " And Marst.PublishTime >= '".date('Y-m-d', strtotime('-7 day'))."' And Marst.PublishTime <= '".date('Y-m-d',time())."'";
					break;
				case 3:
					$sql .= " And Marst.PublishTime >= '".date('Y-m-d', strtotime('-30 day'))."' And Marst.PublishTime <= '".date('Y-m-d',time())."'";
					break;
			}
		}
		
		if(!empty($queryArr['startDate'])){
			$sql .= " And Marst.PublishTime >= '".$queryArr['startDate']."'";
		}
		
		if(!empty($queryArr['endDate'])){
			$sql .= " And Marst.PublishTime <= '".$queryArr['endDate']."'";
		}
		$result = $this->query($sql);
		$clickNum = 0;
		$pcClickNum = 0;
		$mobileClickNum = 0;
		$commentNum = 0;
		$shareNum = 0;
		$imageCollectiveNum = 0;
		
		while($result->fetch_assoc()){
			$clickNum = $result->getData('ClickNum');
			$pcClickNum = $result->getData('PcClickNum');
			$mobileClickNum = $result->getData('MobileClickNum');
			$commentNum = $result->getData('CommentNum');
			$shareNum = $result->getData('ShareNum');
			$imageCollectiveNum = $result->getData('ImageCollectiveNum');
		}
		if($isEditorSta){
		    $sql="SELECT img.CreateBy,COUNT(DISTINCT img.Id) AS CreateCount,us.Id as UserId,us.UserName,us.RealName,sum(Property.ClickNum) as ClickNum,sum(Property.PcClickNum) as PcClickNum,sum(Property.MobileClickNum) as MobileClickNum,sum(Property.CommentNum) as CommentNum,sum(Property.ShareNum) as ShareNum  FROM ImageCollective img
		          LEFT JOIN User AS us ON img.CreateBy = us.Id";
		    $sql.=" left join ImageCollectiveProperty as Property on img.Id = Property.ImageCollectiveId";
		    if(!empty($queryArr['tagIds'])){
		        $sql.=" left join ImageCollectiveTag as Tag on img.Id = Tag.ImageCollectiveId";
		    }
		    $sql .= " where img.CreateBy<>477 And img.CreateBy != 0";
		    if(!empty($queryArr['createBy'])){
		        if(is_array($queryArr['createBy'])){
		            $sql .= " And img.CreateBy in (".implode(',', $queryArr['createBy']).")";
		        } else {
		            $sql .= " And img.CreateBy = ".$queryArr['createBy'];
		        }
		    }
		    if(!empty($queryArr['tagIds'])){
		        $sql .= " And Tag.TagId in (".$queryArr['tagIds'].")";
		    }
		    
		    if(isset($queryArr['Level'])){
		        $level = (int)$queryArr['Level'];
		        if($level <= 7){
		            $sql .= " And img.Level = ".$level;
		        } else {
		            $level = $level - 7;
		            $sql .= " And img.Level >= ".$level;
		        }
		    }
		    if(!empty($queryArr['title'])){
		        $sql .= " And img.Title like '%".$queryArr['title']."%'";
		    }
		    if(!empty($queryArr['publishTimeType'])){
		        $publishTimeType = (int)$queryArr['publishTimeType'];
		        switch ($publishTimeType){
		            case 1:
		                $sql .= " And img.PublishTime >= '".date('Y-m-d', strtotime('-1 day'))."' And img.PublishTime <= '".date('Y-m-d',time())."'";
		                break;
		            case 2:
		                $sql .= " And img.PublishTime >= '".date('Y-m-d', strtotime('-7 day'))."' And img.PublishTime <= '".date('Y-m-d',time())."'";
		                break;
		            case 3:
		                $sql .= " And img.PublishTime >= '".date('Y-m-d', strtotime('-30 day'))."' And img.PublishTime <= '".date('Y-m-d',time())."'";
		                break;
		        }
		    }
		    
		    if(!empty($queryArr['startDate'])){
		        $sql .= " And img.PublishTime >= '".$queryArr['startDate']."'";
		    }
		    
		    if(!empty($queryArr['endDate'])){
		        $sql .= " And img.PublishTime <= '".$queryArr['endDate']."'";
		    }
		    $sql .= " GROUP BY 	img.CreateBy";
		    $limit ="";
		    if(!isset($queryArr['source'])){
		        $limit = " Limit 0,10";
		        if(!empty($queryArr['page']) && $queryArr['page'] > 1){
		            $startCount = ($queryArr['page'] - 1) * 10 + 1;
		            $limit = " Limit ".$startCount.",10";
		        }
		    }
		    $sql .= $limit;
	        $result = $this->query($sql);
		    $key = 0;
		    $imageCollectiveListCount = $result->getMysqlResult()->num_rows;
		    while($result->fetch_assoc()){
		        $imageCollectiveList[$key]['UserId'] = $result->getData('UserId');
		        $imageCollectiveList[$key]['RealName'] = $result->getData('RealName');
		        $imageCollectiveList[$key]['CreateCount'] = $result->getData('CreateCount');
		        $imageCollectiveList[$key]['ClickNum'] = $result->getData('ClickNum');
		        $imageCollectiveList[$key]['CommentNum'] = $result->getData('CommentNum');
		        $imageCollectiveList[$key]['ShareNum'] = $result->getData('ShareNum');
		        $key++;
		    }
		}
		return array('imageCollectiveNum'=>$imageCollectiveNum,'ClickNum'=>$clickNum,'PcClickNum'=>$pcClickNum,'MobileClickNum'=>$mobileClickNum,'CommentNum'=>$commentNum,'ShareNum'=>$shareNum,'imageCollectiveList'=>$imageCollectiveList,'imageListCount'=>$imageCollectiveListCount);
	}
	
	/**
	 * 动态修改Level
	 * @param int $id
	 * @param int $Level
	 */
	public function setLevel($id,$Level){
		$this->updateById($id, array('Level'=>$Level));
		$sql = "update WapInfo set Level=%s where InfoId = %s and InfoType=%s";
		$this->query($sql,array($Level,$id,\haibao\cms\model\data\WapInfo::INFO_TYPE_IMAGE_COLLECTIVE));
	}
	
	public function updateImageCollectiveCommentNum($imageCollectiveId,$num){
		$sql = "update ImageCollectiveProperty set CommentNum=CommentNum+".$num." where ImageCollectiveId=%s";
		$this->query($sql,array($imageCollectiveId));
	}
	
	public function subtractCommentNum($id){
		$sql = 'update ImageCollectiveProperty set CommentNum=CommentNum-1 where ImageCollectiveId=%s';
		$this->query($sql,array($id));
	}
	
	private function saveRelationTable($model){
		//$this->saveImageCollectiveArticle($model);
		$this->saveImageCollectivePic($model);
		$this->saveImageCollectivePro($model);
		$channelTagId = $this->saveImageCollectiveTag($model);
		//$this->saveImageCollectiveKeyWords($model);
		$this->saveEventImageCollective($model);
		return $channelTagId;
	}
	
	private function saveImageCollectiveArticle($model){
		$insertArray = array();
		$itemArray = array();	
		$sql="delete from ImageCollectiveArticle where ImageCollectiveID = %s";
		$this->query($sql,array($model->Id));
		if($model->ImageCollectiveArticle){
			$sql="insert into ImageCollectiveArticle (AritcleId,ImageCollectiveID) values ";
			foreach($model->ImageCollectiveArticle as $key => $value){
				array_push($itemArray,'(%s,%s)');
				array_push($insertArray,$value);
				array_push($insertArray,$model->Id);
			}
			$sql.=join(',',$itemArray);
			$this->query($sql,$insertArray);
		}	
	}
	
	private function saveImageCollectiveKeyWords($model){
		$insertArray = array();
		$itemArray = array();
		$sql="delete from ImageCollectiveKeywords where ImageCollectiveId  = %s";
		$this->query($sql,array($model->Id));
		if($model->ImageCollectiveKeywords){
			$sql="insert into ImageCollectiveKeywords (ImageCollectiveId,KeywordsId) values ";
			foreach($model->ImageCollectiveKeywords as $key =>$value){
				array_push($itemArray,'(%s,%s)');
				array_push($insertArray,$model->Id);
				array_push($insertArray,$value);
			}		
			$sql.=join(',',$itemArray);
			$this->query($sql,$insertArray);
		}
	}
	
	private function saveImageCollectiveTag($model){
		$insertArray = $tagIds = array();
		$itemArray = array();
		$sql="delete from ImageCollectiveTag where ImageCollectiveId  = %s";
		$this->query($sql,array($model->Id));
		$channelTagId = 310;
		if($model->ImageCollectiveTag){
			foreach($model->ImageCollectiveTag as $value){
				$tagIds[] = $value->TagId;
			}
			$tagTrees = \haibao\cms\business\Tag::loopGetParentTag($tagIds);
			$sql="insert into ImageCollectiveTag (ImageCollectiveId,TagId,IsPrimaiy,ParentId,TagTree) values";
			foreach($model->ImageCollectiveTag as $key => $value){
				array_push($itemArray,'(%s,%s,%s,%s,%s)');
				array_push($insertArray,$model->Id);
				array_push($insertArray,$value->TagId);
				array_push($insertArray,$value->IsPrimaiy);
				array_push($insertArray,$value->ParentId);
				array_push($insertArray,isset($tagTrees[$value->TagId]) ? $tagTrees[$value->TagId] : '#');
				if($value->IsPrimaiy){
					$channelTagId = $value->ParentId;
				}
			}
			$sql.=join(',',$itemArray);
			$this->query($sql,$insertArray);
		}
		return $channelTagId;
	}
	
	private function saveEventImageCollective($model){
		$sql="delete from EventImageCollective where ImageCollectiveId = %s ";
		$this->query($sql,array($model->Id));
		if($model && $model->EventImageCollective->EventId){
			$model->EventImageCollective->ImageCollectiveId = $model->Id;
			$this->add($model->EventImageCollective);
		}
	}
}
